<?php


namespace coco;


use coco\client\Redis;
use coco\traits\Singleton;

class Cache
{
    use Singleton;

    protected $handle;

    private function __construct(array $option = [])
    {
        $cache_config = Config::getInstance()->get('cache');
        $reids_config = Config::getInstance()->get('redis');
        $host = $option['host'] ?? $cache_config['redis_host'] ?? $reids_config['host'] ?? '127.0.0.1';
        $option = [
            'port' => $option['port'] ?? $cache_config['redis_port'] ?? $reids_config['port'] ?? 6379,
            'password' => $option['password'] ?? $cache_config['redis_password'] ?? $reids_config['password'] ?? '',
            'db' => $option['db'] ?? $cache_config['redis_db'] ?? $reids_config['db'] ?? '',
            'reconnect' => $option['reconnect'] ?? $cache_config['redis_reconnect'] ?? $reids_config['reconnect'] ?? 10,
        ];
        $this->handle = new Redis($host, $option);
    }

    public function set(string $name, $value, int $expire = 604800): bool
    {
        if ($expire < 0) {
            $expire = 604800;//7天
        }
        if (!empty($expire)) {
            return $this->handle->setex($name, $expire, serialize($value));
        } else {
            return $this->handle->set($name, serialize($value));
        }

    }

    public function get(string $name)
    {
        if (false === $value = $this->handle->get($name)) {
            return false;
        }
        return unserialize($value);
    }

    public function del(string $name): bool
    {
        return $this->handle->del($name);
    }
}